//
//  DynamicViewController.swift
//  BusinessIOS
//
//  Created by Rain on 2018/11/2.
//  Copyright © 2018 XingJian Li. All rights reserved.
//

import UIKit
import Alamofire

class DynamicViewController: UIViewController {
    
    var numString : String!
    var tableView  : UITableView!
    
    var bigDynamicArray = [DynamicModel]()

    
    var DynamicArray = [DynamicModel]()
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
     var index = 0
    var userID: String!

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = bgGrayColor;
        
        navigationItem.title="投资动态"
        tableView = UITableView(frame:self.view.frame, style:.plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none

        tableView.tableFooterView = UIView.init()
        
        
        tableView.register(NSClassFromString("DynamicTableViewCell"), forCellReuseIdentifier: "DynamicTableViewCell")
       
     
       self.view.addSubview(tableView)
        tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
       
        // 下拉刷新
         header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        // 现在的版本要用mj_header
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
        

        
       
        
        
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新")
        
        self.DynamicArray.removeAll()
        self.bigDynamicArray.removeAll()
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/article/getArticleList"
        
        let json = "{\"newsClassId\":\"\(numString!)\",\"start\":\"\(0)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        print("json====\(json)")
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
   
        Alamofire.request(request).responseJSON {(response) in
            
            
            
            print(response)
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   DynamicModel()
                    
                    
                    model1.createtime = dataDic["createtime"].string
                    
                    model1.title = dataDic["title"].string
                    
                    model1.ids = dataDic["id"].string
                    self.DynamicArray.append(model1)
                    
                    
                   
                    
                }
              
                
                self.bigDynamicArray.append(contentsOf: self.DynamicArray)
                
                 print("bigDynamicArray====\(self.bigDynamicArray.count)")
                self.tableView.reloadData()
                
                self.tableView.mj_header.endRefreshing()
            }else{
                self.tableView.mj_header.endRefreshing()
            }
            
        }
        
       
        
        

    }
    
    // 底部刷新
  
    @objc func footerRefresh(){
        
        self.DynamicArray.removeAll()
   
        index += 1
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/article/getArticleList"
        
        let json = "{\"newsClassId\":\"\(numString!)\",\"start\":\"\(index)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        print("json====\(json)")
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            
            print(response)
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   DynamicModel()
                    
                    
                    model1.createtime = dataDic["createtime"].string
                    
                    model1.title = dataDic["title"].string
                    
                    model1.ids = dataDic["id"].string
                    self.DynamicArray.append(model1)
                    
                    
                 
                    
                }
                
                self.bigDynamicArray.append(contentsOf: self.DynamicArray)
                
                   print("DynamicArray====\(self.bigDynamicArray.count)")
                self.tableView.reloadData()
                self.tableView.mj_footer.endRefreshing()
                
            }else{
                self.tableView.mj_footer.endRefreshing()
            }
            
        }
        
       
        
        
       
     
    }
    

    
    
    func loadData(){
        
    
    }


}
extension DynamicViewController: UITableViewDelegate, UITableViewDataSource {
  
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bigDynamicArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let dynamicModel:DynamicModel = self.bigDynamicArray[indexPath.row]
        
        let cell = DynamicTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "DynamicTableViewCell")
        
        
         cell.investmentDynamicsWithModel(model: dynamicModel)
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     
     
      let dynamicModel:DynamicModel = self.bigDynamicArray[indexPath.row]
        
        
        let WebVC =  WebViewController()
        WebVC.numInteger = dynamicModel.ids
        self.navigationController?.pushViewController(WebVC , animated: true)
      
    }

    
}
